package com.hnepri.fang.ftx.fetch;

import com.hnepri.fang.ftx.fetch.residentialDetail.ResidentialDetailThread;
import com.hnepri.fang.ftx.model.Residential;
import com.hnepri.util.DBUtil;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResidentialDetailFetch {
    private String city;
    private String storePath;
    public ResidentialDetailFetch(String city, String storePath) {
        this.city = city;
        this.storePath = storePath;
    }

    /**
     * 从数据库中获取小区简介
     * @return
     */
    public List<Residential> getResidentialQuartersList() {
        List<Residential> ls = new ArrayList<>();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //这个sql是查找没有明细的小区简介数据
        String sql = "SELECT t1.id,t1.domain " +
                "from xiaoqu t1 where t1.city='" + city + "' " +
                "and not EXISTS(SELECT 1 from xiaoqudetail t2 where t1.id=t2.fid)";

        try {
            con = DBUtil.getConnection();
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            Residential obj = null;
            while (rs.next()) {
                obj = new Residential();

                String id = rs.getString(1);
                String url = rs.getString(2);
                obj.setId(id);
                obj.setDomain(url);

                ls.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                DBUtil.closeResource(con, ps, rs);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return ls;
    }

    /**
     * 开启线程以获取数据
     * @param threadLen   线程数量-根据电脑cpu核心数以确定
     */
    public void go(int threadLen) {
        String path = storePath + "/" + city + "/mingxi";

        File f = new File(path);
        if (!f.exists()) {
            f.mkdir();
        }


        List<Residential> ls = getResidentialQuartersList();
        int detailSize = ls.size();
        int groupStep = detailSize / threadLen;//每个线程查询多少页面

        int extralPage = detailSize % threadLen;

        int start = 0;
        for(int i = 0; i < threadLen; i++) {
            new ResidentialDetailThread(path, ls, start, start + groupStep - 1).start();
            start += groupStep;
        }
        if (extralPage > 0) {
            new ResidentialDetailThread(path, ls, start, detailSize - 1).start();
        }
    }
    public static void main(String[] args) {
        String path = "E:/小区";
        new ResidentialDetailFetch("jiyuan",path).go(4);
    }
}
